<?php

namespace App\Module;

use App\depository\TsBatchDep;
use App\depository\TsLogDep;
use App\depository\TsOrderDep;
use App\Enum\batchEnum;
use App\Models\TsExportModel;
use App\Models\TsLogModel;
use App\Models\TsSystemModel;
use Illuminate\Support\Str;

class OrderModule extends BaseModule
{
    public function index()
    {
        return self::response(['hello' => 'hello world']);
    }

    public function import($request)
    {

        $param = $request->input();
        $count = $param['count'];

        $batchNo = md5(time() . str::random(5));
        $file = $request->file('file');
        $extension = $file->getClientOriginalExtension();
        if ($extension != 'xlsx') {
            return self::response([], '请导入后缀是 xlsx 的文件', 200);
        }

        $request->file('file')->storeAs(
            'orders', $batchNo . '.' . $extension
        );

        $dep = new TsBatchDep();
        $data = [
            "batch_no" => $batchNo,
            "status" => 1,
            "count" => $count
        ];

        $dep->add($data);

        return self::response();

    }

    public function batchList($request)
    {
        $param = $request->input();

        $param['per_page'] = $param['per_page'] ?? 10;
        $param['current_page'] = $param['current_page'] ?? 1;

        $dep = new TsBatchDep();
        $resList = $dep->list($param);

        $list = $resList->getCollection()->toBase();
        $data['list'] = $list->map(function ($item) {
            return [
                "id" => $item->id,
                "batch_no" => $item->batch_no,
                "rate" => $item->rate . "%",
                "rows" => $item->rows,
                "expect_rows" => $item->expect_rows,
                "status_show" => batchEnum::$statusArr[$item->status],
                "count" => $item->count,
                "created_at" => $item->created_at->toDateTimeString()
            ];
        });

        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];

        return self::response($data);
    }

    public function orderList($request)
    {

        $param = $request->input();

        $dep = new TsOrderDep();

        $config = TsSystemModel::first();

        if (!isset($param['limit']) || !$param['limit']) {
            $param['limit'] = 500;
        }
        $count = $dep->apiListCount($param);
        $realNum = $count > $param['limit'] ? $param['limit'] : $count;

        TsLogModel::insert(['ip'=> $request->header('x-forwarded-for'),'province'=> $param['province']?? "",'city' => $param['city']??"",'limit'=> $param['limit'] ]);

        if ($realNum > $config->max_limit) {
            $token = md5(time() . str::random(5));
            $addData = [
                "token" => $token,
                "province" => $param['province'] ?? "",
                "city" => $param['city'] ?? "",
                "limit" => $param['limit'],
                "status" => 1
            ];
            TsExportModel::insert($addData);

            $data['token'] = $token;
        }else{
            $resList = $dep->apiList($param);

            $data['list'] = $resList->map(function ($item) use($dep){
                $dep->upd($item->id,['count' => $item->count - 1]);
                return [
                    "name" => $item->name,
                    "orderid" => $item->orderid,
                    "getprovince" => $item->getprovince,
                    "getcity" => $item->getcity,
                ];
            });

        }

        return self::response($data);
    }

    public function systemDetail($request){

        $res = TsSystemModel::first();

        $data = [
            "id"   => $res->id,
            "max_limit" => $res->max_limit,
        ];

        return self::response($data);
    }

    public function systemEdit($request){

        $param = $request->input();

        $data = [
          "max_limit" => $param['max_limit']
        ];

        TsSystemModel::where('id',$param['id'])->update($data);

        return self::response();

    }

    public function logList($request){

        $param = $request->input();

        $param['per_page'] = $param['per_page'] ?? 10;
        $param['current_page'] = $param['current_page'] ?? 1;

        $dep = new TsLogDep();
        $resList = $dep->list($param);

        $list = $resList->getCollection()->toBase();
        $data['list'] = $list->map(function ($item) {
            return [
                "id" => $item->id,
                "ip" => $item->ip,
                "province" => $item->province,
                "city" => $item->city,
                "limit" => $item->limit,
                "created_at" => $item->created_at->toDateTimeString()
            ];
        });

        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];

        return self::response($data);
    }

    public function login($request){

        $param = $request->input();

        if($param['username'] === env('LOGIN_USER_NAME') && $param['password'] === env('LOGIN_PASSWORD')){
            $data =[
                "username" => env('LOGIN_USER_NAME')
            ];
            return self::response($data);
        }
        return self::response([],"用户名或密码错误",500);
    }
}

